# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 15:04:37 2017

@author: qiang.qian
"""
import json
import requests
import datetime
import sys
import csv

stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

path = 'D:\\QIAN\\CODE\\oschina\\userprofile\\cloud\\'
file = '16'
sources_file = path + 'mails_' + file + '.txt'
result_file = open(path + 'result_' + file + '_' + stamp + ".txt", "w")


def desmails(infos):
    url = 'http://coreinfo.arc.ctripcorp.com/decryptservice/api/batchdecrypt'
    headers = {'content-type': 'application/json'}
    values = {
            "appId":"100009072",
            "op":"qiang.qian",
            "infos":[]
    }
    
    for info in infos:
        value = {}
        value['key'] = info[1]
        value['type'] = 2
        values['infos'].append(value)
  
    try:
        data = json.dumps(values)

        res = requests.post(url=url,data=data,headers=headers)
        j = json.loads(res.text)
        
        mails = j['result']['2']['data']
        return mails
    except Exception as e:
        print("Unexpected error:", sys.exc_info()[0])
        print(infos)
        print(values)
        return {}

def savemails(mails):
    for (k,v) in  mails.items():
        result_file.write("{0}\t{1}\n".format(k,v))

# main
with open(sources_file, 'r',encoding='utf8') as f:
    reader = csv.reader(f,delimiter='\t')
    lines = list(reader)

try:
    i = 0
    infos = []
    for info in lines:
        infos.append(info)
        i = i + 1
        if(i % 10 == 0):
            mails=desmails(infos)
            infos.clear();
            savemails(mails)
            result_file.flush()
    if(infos.count() > 0):
            mails=desmails(info)
            savemails(mails)
    print("done")
except KeyboardInterrupt:
    print("break")
    sys.exit()
finally:
    result_file.flush()
    result_file.close()

    